#!/bin/sh

compress_html()
{
    local SRC=$1
    local DST=$2

    echo "Compressing $SRC..."
    awk -f ./httpd/tools/remcomm.awk "$SRC" > ./_install/www/tmp.html
    xmllint --html --noblanks ./_install/www/tmp.html > "$DST"
    rm ./_install/www/tmp.html
}

set -e

SCRIPT_DIR=$(cd `dirname $0` && pwd)
cd $SCRIPT_DIR

mkdir -p ./_install/www/cgi-bin
mkdir -p ./_install/www/img
mkdir -p ./_install/www/css
mkdir -p ./_install/www/js
mkdir -p ./_install/www/pages
ln -s /tmp/sd/record ./_install/www/record

echo "Compressing CSS files..."
#find ./httpd/htdocs/css/* ! -name all.css -exec cat {} \+  > ./_install/www/htdocs/css/tmp.css
cat ./httpd/htdocs/css/normalize.min.css ./httpd/htdocs/css/skeleton.min.css ./httpd/htdocs/css/custom.css > ./_install/www/css/tmp.css
yui-compressor --type css -o ./_install/www/css/all.css ./_install/www/css/tmp.css
rm ./_install/www/css/tmp.css

echo "Compressing JS files..."
cp ./httpd/htdocs/js/jquery.min.js ./_install/www/js/jquery.min.js
cat ./httpd/htdocs/js/utils.js ./httpd/htdocs/js/app.js ./httpd/htdocs/js/modules/*.js > ./_install/www/js/tmp.js
yui-compressor --type js -o ./_install/www/js/all.js ./_install/www/js/tmp.js
rm ./_install/www/js/tmp.js

echo "Compressing HTML files..."

compress_html ./httpd/htdocs/index.html ./_install/www/index.html

# Compress pages
for PAGE in ./httpd/htdocs/pages/*.html ; do
    PAGE_NAME="${PAGE##*/}"
    compress_html ./httpd/htdocs/pages/$PAGE_NAME ./_install/www/pages/$PAGE_NAME
done

echo "Copying image files..."
cp -R ./httpd/htdocs/img/. ./_install/www/img/

# To exlude more directories add the following line to the find command (after "-type f")
# -not \( -path './_install/www/DIRECTORY_NAME/*' -prune \)
echo "Aplying GZIP Compression to files..."
find ./_install/www/* -type f -not \( -path './_install/www/cgi-bin/*' -prune \) -exec gzip -f -9 {} +

echo "Copying the cgi-bin folder..."
cp ./httpd/cgi-bin/* ./_install/www/cgi-bin

echo "Compilation succeeded."
